//
//  LZNewRegisterViewController.m
//  laziz_Merchant
//
//  Created by xbnzd on 17/3/16.
//  Copyright © 2017年 XBN. All rights reserved.
//

#import "LZNewRegisterViewController.h"
#import "UIViewController+NavigationItemSetting.h"
#import "GVUserDefaults+LZProperties.h"
#import "LZNotificationPresenter.h"
#import "LZAreaCodeViewController.h"
#import "LZCommonWebViewController.h"
#import "LZUserInfoPresenter.h"
#import "LZPhoneRegisterView.h"
#import "LZEmailRegisterView.h"
#import "LZCurrentUserInfo.h"
#import "UIView+Rotation.h"
#import "AppDelegate.h"
#import "LZRemindView.h"
#import "MJExtension.h"
#import "LZUserModel.h"
#import "LZAlertView.h"
#import "extobjc.h"
#import "Masonry.h"
#import "NSString+LZRegex.h"

@interface LZNewRegisterViewController ()
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *logoTopToSuperViewCST;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *registerModeBgViewTopToTitleViewCSt;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *registerModeBgViewHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *registerBtnBottomToBtnCST;

@property (weak, nonatomic) IBOutlet UIButton *registerBtn;
@property (weak, nonatomic) IBOutlet UIButton *changeRegisterModeBtn;
@property (weak, nonatomic) IBOutlet UIView *registerBgView;

@property (strong, nonatomic) UINavigationController *navVC;
@property (strong, nonatomic) LZAreaCodeViewController *areaCodeVC;
@property (strong, nonatomic) LZPhoneRegisterView *phoneRegisterView;
@property (strong, nonatomic) LZEmailRegisterView *emailRegisterView;
@property (nonatomic, strong) LZUserInfoPresenter * userInfoPresenter;
@property (assign, nonatomic) RegisterType registerType;
@property (nonatomic, strong) NSTimer * timer;          //验证码倒计时
@property (nonatomic, assign) int count;

@end

@implementation LZNewRegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self configureUI];
    
    [self configNavigationBar];
}

- (BOOL)fd_prefersNavigationBarHidden {
    return YES;
}

- (void)navbarBackButtonClickAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - private method
- (void)addRegisterViewForRegisterType
{
    if (self.registerType == kRegisterType_phone) {
        
        self.emailRegisterView.hidden = YES;
        self.phoneRegisterView.hidden = NO;
        
    }else if (self.registerType == kRegisterType_email){
       
        self.phoneRegisterView.hidden = YES;
        self.emailRegisterView.hidden = NO;
    }
}


/**
 手机注册
 */
- (void)registerForPhone
{
    if (self.phoneRegisterView.isAgreement == NO) {
        [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"]
                         andContent:LZLocalizedString(@"read_and_agree_service", @"")];
        return;
    }
    
    if (self.phoneRegisterView.phoneTF.text.length <= 0) {
        [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"] andContent:LZLocalizedString(@"login_enter_mobile", @"")];
        return;
    }
    
    NSString * userName = [NSString stringWithFormat:@"%@%@",
                           self.phoneRegisterView.areaCodeLabel.text,
                           self.phoneRegisterView.phoneTF.text];
    
    NSString * verifiCode = [NSString stringWithFormat:@"%@", self.phoneRegisterView.verificationCodeTF.text];
    
    if (verifiCode.length <= 0) {
        [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"] andContent:LZLocalizedString(@"login_enter_verifi_code", @"")];
        return;
    }
    
    NSString * passwordStr = [NSString stringWithFormat:@"%@", self.phoneRegisterView.passwordTF.text];
    if (passwordStr.length <= 0) {
        [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"] andContent:LZLocalizedString(@"enter_password", @"")];
        return;
    } else if (passwordStr.length > 0 && passwordStr.length < 6) {
        [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"] andContent:LZLocalizedString(@"enter_password_6_chart", @"")];
        return;
    }
    
    DLog(@"userName: %@, verifiCodeTextField=%@ :  passwordStr: %@", userName, verifiCode,  passwordStr);
    
    [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:YES];
    
    @weakify(self);
    [self.userInfoPresenter userRegisterCellPhone:userName andPassword:passwordStr andVerificationCode:verifiCode andonSuccess:^(id data) {
        
        DLog(@"手机注册成功：\r%@", data);
        @strongify(self);
        [self stopLoadingViewForView:self.view];
        
        //登录类型
        NSDictionary *dataDic = (NSDictionary *)data;
        LZCurrentUserInfo *userInfo = [LZCurrentUserInfo mj_objectWithKeyValues:dataDic[@"data"]];
        if (userInfo) {
            [LZUserModel Instance].userInfo = userInfo;
            [GVUserDefaults standardUserDefaults].phoneAreaCode = self.phoneRegisterView.areaCodeLabel.text;
            [GVUserDefaults standardUserDefaults].userId = userInfo.userId;
            [GVUserDefaults standardUserDefaults].userToken = userInfo.token;
            [GVUserDefaults standardUserDefaults].userId = userInfo.userId;
            [LZNotificationPresenter setNotificationAlias:userInfo.userId];
            [GVUserDefaults standardUserDefaults].isSetPassword = userInfo.hasPassword;
            [GVUserDefaults standardUserDefaults].loginType = kLogin_phone;
            [GVUserDefaults standardUserDefaults].userType = userInfo.userType;
            [GVUserDefaults standardUserDefaults].email = userInfo.email;
            [GVUserDefaults standardUserDefaults].cellphone = userInfo.cellphone;
            
            //商户状态 0 商户未认证 1 待审核 2 正常 3 审核退回 4 已停用
            [GVUserDefaults standardUserDefaults].authType = userInfo.merchantState;
            if (userInfo.merchantState == kAuthType_completeAuth) {
                [GVUserDefaults standardUserDefaults].sellerId = userInfo.sellerId;
            }
        }
        //登陆成功，切换
        AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
        [appDelegate setRootForHomeVCWithIsShowLeadingView:NO];
        
    } onFail:^(NSString *fail) {
        @strongify(self);
        [self stopLoadingViewForView:self.view];
        
        if ([fail isEqualToString:@"0400001"] || [fail isEqualToString:@"0100010"] || [fail isEqualToString:@"0500001"]) {
            [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"] andContent:LZLocalizedString(@"enter_invalid_verifi", @"")];//0400001 验证码错误
        }
        else if ([fail isEqualToString:@"0400004"]) {
            [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"] andContent:LZLocalizedString(@"phone_is_register", @"")]; //0400004 当前手机号已经被注册
        }
        else if ([fail isEqualToString:@"0400008"]){
            [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"] andContent:LZLocalizedString(@"register_failed", @"")]; //0400008 注册失败
        }
        
        DLog(@"手机注册失败：\r%@", fail);
    }];

}


/**
 邮箱注册
 */
- (void)registerForEmail
{
    if (self.emailRegisterView.isAgreement == NO) {
        [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"]
                         andContent:LZLocalizedString(@"read_and_agree_service", @"")];
        return;
    }
    
    if (self.emailRegisterView.emailTF.text.length <= 0) {
        [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"] andContent:LZLocalizedString(@"login_alert_enter_eMail_address", @"")];
        return;
    }
    
    if (![self.emailRegisterView.emailTF.text isEmailAddress]) {
        [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"] andContent:LZLocalizedString(@"invalid_email_remind", @"")];
        return;
    }
    
    NSString * userName = [NSString stringWithFormat:@"%@",
                           self.emailRegisterView.emailTF.text];
    
    NSString * passwordStr = [NSString stringWithFormat:@"%@", self.emailRegisterView.passwordTF.text];
    if (passwordStr.length <= 0) {
        [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"] andContent:LZLocalizedString(@"enter_password", @"")];
        return;
    } else if (passwordStr.length > 0 && passwordStr.length < 6) {
        [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"] andContent:LZLocalizedString(@"enter_password_6_chart", @"")];
        return;
    }
    
    DLog(@"userName: %@,, passwordStr: %@", userName, passwordStr);
    
    [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:YES];
    
    @weakify(self);
    [self.userInfoPresenter registerForEmailWithEmail:userName Password:passwordStr Success:^(id data) {
        DLog(@"邮箱注册成功：\r%@", data);
        @strongify(self);
        [self stopLoadingViewForView:self.view];
        
        //登录类型
        NSDictionary *dataDic = (NSDictionary *)data;
        LZCurrentUserInfo *userInfo = [LZCurrentUserInfo mj_objectWithKeyValues:dataDic[@"data"]];
        if (userInfo) {
            [LZUserModel Instance].userInfo = userInfo;
            [GVUserDefaults standardUserDefaults].userId = userInfo.userId;
            [GVUserDefaults standardUserDefaults].userToken = userInfo.token;
            [GVUserDefaults standardUserDefaults].userId = userInfo.userId;
            [LZNotificationPresenter setNotificationAlias:userInfo.userId];
            [GVUserDefaults standardUserDefaults].isSetPassword = userInfo.hasPassword;
            [GVUserDefaults standardUserDefaults].loginType = kLogin_eMail;
            [GVUserDefaults standardUserDefaults].userType = userInfo.userType;
            [GVUserDefaults standardUserDefaults].email = userInfo.email;
            [GVUserDefaults standardUserDefaults].cellphone = userInfo.cellphone;
            
            //商户状态 0 商户未认证 1 待审核 2 正常 3 审核退回 4 已停用
            [GVUserDefaults standardUserDefaults].authType = userInfo.merchantState;
            if (userInfo.merchantState == kAuthType_completeAuth) {
                [GVUserDefaults standardUserDefaults].sellerId = userInfo.sellerId;
            }
        }
        //登陆成功，切换
        AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
        [appDelegate setRootForHomeVCWithIsShowLeadingView:NO];

    } Failure:^(NSString *fail) {
        @strongify(self);
        [self stopLoadingViewForView:self.view];
        
        if ([fail isEqualToString:@"0400008"]){
            [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"] andContent:LZLocalizedString(@"register_failed", @"")]; //0400008 注册失败
            
        }else if ([fail isEqualToString:@"0400039"]){
        
            [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"] andContent:LZLocalizedString(@"email_is_register", @"")]; //邮箱已经注册过
        }else if ([fail isEqualToString:@"0400045"]){
            [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"] andContent:LZLocalizedString(@"invalid_email_remind", @"")];
        }
        
        DLog(@"邮箱注册失败：\r%@", fail);
    }];
}


/**
 点击协议事件
 */
- (void)clickAgreementAciont
{
    @weakify(self);
    self.phoneRegisterView.clickAgreementLabelBlock = ^(){
        @strongify(self);
        LZCommonWebViewController *vc = [[LZCommonWebViewController alloc] init];
        vc.webCode = kWebState_service;
        [self.navigationController pushViewController:vc animated:YES];
    };
    
    self.emailRegisterView.clickAgreementLabelBlock = ^(){
        @strongify(self);
        LZCommonWebViewController *vc = [[LZCommonWebViewController alloc] init];
        vc.webCode = kWebState_service;
        [self.navigationController pushViewController:vc animated:YES];
    };
    
}

/**
 点击验证码按钮事件
 */
- (void)clickVerificationCodeBtnAction
{
    @weakify(self);
   self.phoneRegisterView.clickVerificationCodeBtnBlock = ^()
    {
        @strongify(self);
        if (self.phoneRegisterView.phoneTF.text.length <= 0) {
            [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"] andContent:LZLocalizedString(@"login_enter_mobile", @"")];
            return;
        }
        //验证码类型（1注册，2快捷登录，3身份验证，4绑定手机）
        NSString * mobileStr = [NSString stringWithFormat:@"%@%@",self.phoneRegisterView.areaCodeLabel.text,self.phoneRegisterView.phoneTF.text];
        
        //显示倒计时
        [self startTimer];
        
        [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:YES];
        
        [self.userInfoPresenter checkThePhoneHaveBeenRegister:mobileStr Success:^(id data) {
            [self.userInfoPresenter userGetVerificationPhoneNum:mobileStr andonSuccess:^(id data) {
                @strongify(self);
                DLog(@"获取验证码：\r%@", data);
                [self stopLoadingViewForView:self.view];
#if DEBUG
                self.phoneRegisterView.verificationCodeTF.text = [NSString stringWithFormat:@"%@", [data objectForKey:@"data"]];
#endif
                
            } onFail:^(NSString *fail) {
                @strongify(self);
                DLog(@"获取验证码失败：\r%@", fail);
                [self stopLoadingViewForView:self.view];
                [self stopTimer];
                
                if ([fail isEqualToString:@"9999999"]) {
//                    [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"]
//                                     andContent:LZLocalizedString(@"send_code_maxnum_remind", nil)];
                    LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"send_code_maxnum_remind", nil)
                                                                     andImage:[UIImage imageNamed:@"错误提示"]
                                                            cancelButtonTitle:LZLocalizedString(@"confirm", nil)
                                                            otherButtonTitles:nil, nil];
                    [alert show];
                    
                }
                else {
                    [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"]
                                     andContent:LZLocalizedString(@"vificode_failed", nil)];
                    
                }
            } ];

        } Failure:^(NSString *fail) {
            @strongify(self);
            [self stopLoadingViewForView:self.view];
            [self stopTimer];
            if ([fail isEqualToString:@"0400004"]) {
                [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"] andContent:LZLocalizedString(@"phone_is_register", @"")]; //0400004 当前手机号已经被注册
            }
        }];
        
        

    };
}


/**
 点击区号选择事件
 */
- (void)clickAreaCodeLabelAction
{
    @weakify(self);
    self.phoneRegisterView.clickAreaCodeLabelBlock = ^(){
    
        @strongify(self);
        [self presentViewController:self.navVC animated:YES completion:^{
            
        }];
        self.areaCodeVC.SelectedAreaCodeBlock = ^(NSString *codeStr){
            @strongify(self);
            self.phoneRegisterView.areaCodeLabel.text = codeStr;
        };
    };
}

#pragma mark - 倒计时 开启 关闭倒计时
- (void)startTimer {
    
    self.phoneRegisterView.timeDownLabel.text = @"60s";
    [self.timer invalidate];
    self.count = 0;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1
                                                  target:self
                                                selector:@selector(updateTime)
                                                userInfo:nil
                                                 repeats:YES];
    
    self.phoneRegisterView.timeDownLabel.hidden = NO;
    self.phoneRegisterView.verificationCodeBtn.hidden = YES;
}

- (void)stopTimer {
    [self.timer invalidate];
    self.phoneRegisterView.timeDownLabel.hidden = YES;
    self.phoneRegisterView.verificationCodeBtn.hidden = NO;
}

- (void)updateTime
{
    self.count ++;
    if (self.count >= 60)
    {
        [self stopTimer];
        return;
    }
    
    self.phoneRegisterView.timeDownLabel.text = [NSString stringWithFormat:@"%is", 60-self.count];
    
    if (self.count == 60) {
        self.phoneRegisterView.timeDownLabel.hidden = YES;
        self.phoneRegisterView.verificationCodeBtn.hidden = NO;
    }
}

#pragma mark - btn action
- (IBAction)registerBtnAction:(id)sender {
    if (self.registerType == kRegisterType_email) {
        [self registerForEmail];
    }else if (self.registerType ==kRegisterType_phone){
        [self registerForPhone];
    }
}

- (IBAction)changeRegisterModeBtnAction:(id)sender {
    
    self.phoneRegisterView.phoneTF.text = nil;
    self.phoneRegisterView.verificationCodeTF.text = nil;
    self.phoneRegisterView.passwordTF.text = nil;
    
    self.emailRegisterView.emailTF.text = nil;
    self.emailRegisterView.passwordTF.text = nil;
    
    if (self.registerType == kRegisterType_phone) {
        
        self.registerType = kRegisterType_email; //默认手机注册
        [self.changeRegisterModeBtn setTitle:LZLocalizedString(@"register_by_phone", nil) forState:UIControlStateNormal];
        
    }else if (self.registerType == kRegisterType_email){
        
        self.registerType = kRegisterType_phone; //默认手机注册
        [self.changeRegisterModeBtn setTitle:LZLocalizedString(@"register_by_email", nil) forState:UIControlStateNormal];
    }
    
    [self addRegisterViewForRegisterType];
}

#pragma mark - UI
- (void)configureUI
{
    self.umLogPageViewName = @"注册页面";
    _userInfoPresenter = [[LZUserInfoPresenter alloc] init];
    self.titleLabel.text = LZLocalizedString(@"login_register", nil);
    [self.registerBtn setTitle:LZLocalizedString(@"login_register", nil) forState:UIControlStateNormal];
    
    self.view.backgroundColor = UIColorFromRGB(0x333333, 1);
    
    [self lz_setCustomBarAlpha:0];
    
    self.registerType = kRegisterType_phone; //默认手机注册
    [self.changeRegisterModeBtn setTitle:LZLocalizedString(@"register_by_email", nil) forState:UIControlStateNormal];
    
    self.registerBtn.backgroundColor = UIColorFromRGB(0x33a928, 1);
    self.registerBtn.layer.cornerRadius = 22.;
    self.registerBtn.layer.masksToBounds = YES;
    
    
    GET_SCREEN_SCALE(scale);
    self.logoTopToSuperViewCST.constant = 79 *scale;
    self.registerModeBgViewTopToTitleViewCSt.constant = 60 *scale;
    self.registerBtnBottomToBtnCST.constant = 75 *scale;
    
    [self.registerBgView addSubview:self.emailRegisterView];
    [self.registerBgView addSubview:self.phoneRegisterView];

    [self.phoneRegisterView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(0);
        make.top.mas_equalTo(0);
        make.trailing.mas_equalTo(0);
        make.height.mas_equalTo(200);
    }];

    
    [self.emailRegisterView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(0);
        make.top.mas_equalTo(0);
        make.trailing.mas_equalTo(0);
        make.height.mas_equalTo(150);
    }];
    self.emailRegisterView.hidden = YES;
}

- (void)configNavigationBar{
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, 60, 40);
    [btn addTarget:self action:@selector(navbarBackButtonClickAction) forControlEvents:UIControlEventTouchUpInside];
    UIImage *image_back = [UIImage imageNamed:@"lz_back_en"];
    [btn setImage:image_back forState:UIControlStateNormal];
    btn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, CGRectGetWidth(btn.bounds)-image_back.size.width);
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0) {
        [btn setLanguageRotaion];
    }
    
    [self hiddenBarNavigationItemSetting:@[btn] type:NAVIGATIONITEMSETTING_LEFT];
    [self lz_setCustomBarAlpha:0];
}

#pragma mark - 初始化
- (LZPhoneRegisterView *)phoneRegisterView
{
    if (!_phoneRegisterView) {
        _phoneRegisterView = [[NSBundle mainBundle] loadNibNamed:@"LZPhoneRegisterView" owner:self options:nil].lastObject;
//        _phoneRegisterView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 200);
        
        [self clickVerificationCodeBtnAction];
        [self clickAreaCodeLabelAction];
        [self clickAgreementAciont];
    }
    
    return _phoneRegisterView;
}

- (LZEmailRegisterView *)emailRegisterView
{
    if (!_emailRegisterView) {
        _emailRegisterView = [[NSBundle mainBundle] loadNibNamed:@"LZEmailRegisterView" owner:self options:nil].lastObject;
//        _emailRegisterView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 150);
        
        [self clickAgreementAciont];
    }
    
    return _emailRegisterView;
}

- (UINavigationController *)navVC
{
    if (!_navVC) {
        _navVC = [[UINavigationController alloc] initWithRootViewController:self.areaCodeVC];
        _navVC.navigationBar.translucent = NO;
        _navVC.navigationBar.barTintColor = [UIColor blackColor];
        _navVC.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:[UIFont systemFontOfSize:18]};
    }
    
    return _navVC;
}

- (LZAreaCodeViewController *)areaCodeVC
{
    if (!_areaCodeVC) {
        _areaCodeVC = [[LZAreaCodeViewController alloc] initWithNibName:@"LZAreaCodeViewController" bundle:nil];
    }
    
    return _areaCodeVC;
}
@end
